#include "Sprite2D.h"
#include <glad/glad.h>
#include <glm/gtc/type_ptr.hpp>

Shader *Sprite2D::_shader2D = nullptr;
Mesh *Sprite2D::_meshQuad = nullptr;

Sprite2D::Sprite2D(/* args */)
{
    _update();
}

Sprite2D::~Sprite2D()
{
}

Sprite2D::Sprite2D(const std::string path)
{
    if (!path.empty())
    {
        setTexture(path);
    }
}

Sprite2D::Sprite2D(Texture2D *texture)
{
    if (texture)
    {
        setTexture(texture);
    }
}

void Sprite2D::setTexture(const std::string path)
{
    _texture = new Texture2D(path, TEXTURE_WRAP_CLAMP);
    _update();
}
void Sprite2D::setTexture(Texture2D *texture)
{
    _texture = texture;
    _update();
}

void Sprite2D::_update()
{
    if (Sprite2D::_shader2D == nullptr)
    {
        Sprite2D::_shader2D = new Shader("shader/2d.vs", "shader/2d.fs");
    }
    if (Sprite2D::_meshQuad == nullptr)
    {
        Sprite2D::_meshQuad = Mesh::createPrimitive(PRIMITIVE_QUAD);
    }
}
void Sprite2D::render()
{
    if (_texture != nullptr && Sprite2D::_shader2D != nullptr && Sprite2D::_meshQuad != nullptr)
    {
        _texture->use();

        Sprite2D::_shader2D->use();
        glm::mat4 mat = getMatrix();
        Sprite2D::_shader2D->setMat4("transform",mat);

        Sprite2D::_meshQuad->draw();
    }
}